package com.duobaoyu.dby.supply.biz.service.refund;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.duobaoyu.dby.channel.adapter.enums.biz.refund.AfterSaleStatusEnum;
import com.duobaoyu.dby.channel.adapter.enums.biz.refund.AfterSaleTypeEnum;
import com.duobaoyu.dby.channel.adapter.enums.biz.refund.RefundStatusEnum;
import com.duobaoyu.dby.common.mybatis.config.IdGeneratorSnowflake;
import com.duobaoyu.dby.common.mybatis.util.EnumUtils;
import com.duobaoyu.dby.supply.biz.converter.AfterSaleServiceConverter;
import com.duobaoyu.dby.supply.biz.enums.AfterSaleSourceEnum;
import com.duobaoyu.dby.supply.biz.service.refund.event.AfterSaleStateChangeEvent;
import com.duobaoyu.dby.supply.common.biz.bo.refund.AfterSaleItemOutBO;
import com.duobaoyu.dby.supply.common.biz.bo.refund.AfterSaleOutBO;
import com.duobaoyu.dby.supply.common.biz.bo.refund.AfterSaleStateContext;
import com.duobaoyu.dby.supply.common.biz.bo.refund.AfterSaleWayBillInBO;
import com.duobaoyu.dby.supply.core.common.exception.CustomAssert;
import com.duobaoyu.dby.supply.db.entity.refund.AfterSale;
import com.duobaoyu.dby.supply.db.entity.refund.AfterSaleItem;
import com.duobaoyu.dby.supply.db.entity.refund.AfterSalePickUp;
import com.duobaoyu.dby.supply.db.entity.refund.AfterSalesLogistic;
import com.duobaoyu.dby.supply.db.repository.refund.AfterSaleItemRepository;
import com.duobaoyu.dby.supply.db.repository.refund.AfterSaleRepository;
import com.duobaoyu.dby.supply.db.repository.refund.AfterSalesLogisticsRepository;
import com.duobaoyu.dby.supply.db.repository.refund.AfterSalesPickupRepository;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Created by shuming on 2023/10/12 18:28
 */
@Service
@RequiredArgsConstructor
public class AfterSaleStateMachine {

    private final AfterSaleServiceConverter afterSaleServiceConverter;
    private final AfterSaleRepository afterSaleRepository;
    private final IdGeneratorSnowflake idGeneratorSnowflake;
    private final AfterSaleItemRepository afterSaleItemRepository;
    private final AfterSalesPickupRepository afterSalesPickupRepository;
    private final AfterSalesLogisticsRepository afterSalesLogisticsRepository;

    /**
     * 状态动作
     */
    private final Map<Integer, Action> stateMachine = new HashMap<Integer, Action>() {
        {
            put(AfterSaleStatusEnum.WAIT_REJECT_CONFIRM.getValue(), new WaitRejectConfirmAction());
            put(AfterSaleStatusEnum.TO_BE_SUBMITTED_FOR_CHANNEL.getValue(), new ToBeSubmittedForChannelAction());
            put(AfterSaleStatusEnum.TO_BE_REVIEWED_BY_CHANNEL.getValue(), new ToBeReviewedByChannelAction());
            put(AfterSaleStatusEnum.COMPLETED.getValue(), new CompleteAction());
            put(AfterSaleStatusEnum.CLOSE.getValue(), new CloseAction());
            put(AfterSaleStatusEnum.TO_BE_SENT_BACK_BY_BUYER.getValue(), new ToBeSentBackByBuyerAction());
            put(AfterSaleStatusEnum.PENDING_RECEIPT.getValue(), new PendingReceiptAction());
            put(AfterSaleStatusEnum.CHANNEL_AUDIT_SUCCESS.getValue(), new ChannelAuditSuccessAction());
            put(AfterSaleStatusEnum.TO_BE_CONFIRMED_BY_USER.getValue(), new ToBeConfirmedByUserAction());
            put(AfterSaleStatusEnum.FAIL.getValue(), new DbyAuditRejectAction());
        }
    };

    @Transactional(rollbackFor = Exception.class)
    public Boolean exe(AfterSaleStateContext context) {
        Integer status = context.getCurrentAfterSaleStatus();
        CustomAssert.notNull(status, "售后状态参数缺失");
        CustomAssert.notNull(context, "售后数据缺失");
        CustomAssert.notNull(context.getOperateSource(), "操作源参数缺失");
        if (Objects.equals(status, context.getAfterSale().getStatus())) {
            return Boolean.TRUE;
        }
        if (Objects.isNull(context.getChangeContentOperate())) {
            context.setChangeContentOperate(new AfterSaleStateContext.ChangeContentOperate());
        }
        Boolean ret = stateMachine.get(context.getCurrentAfterSaleStatus()).exe(context);
        if (Objects.nonNull(context.getChangeContentOperate().getNewPickupType())) {
            LambdaQueryWrapper<AfterSalePickUp> queryWrapper = Wrappers.<AfterSalePickUp>lambdaQuery()
                    .eq(AfterSalePickUp::getAfterSaleSn, context.getAfterSale().getAfterSaleSn());
            AfterSalePickUp pickUp = afterSalesPickupRepository.getOne(queryWrapper);
            pickUp.setPickupType(context.getChangeContentOperate().getNewPickupType());
            afterSalesPickupRepository.updateById(pickUp);
        }
        if (ret) {
            AfterSaleOutBO afterSale = context.getAfterSale();
            AfterSaleStateChangeEvent orderEvent = new AfterSaleStateChangeEvent();
            orderEvent.setAfterSaleSn(afterSale.getAfterSaleSn());
            orderEvent.setAfterSaleType(afterSale.getAfterSaleType());
            orderEvent.setOrderSn(afterSale.getOrderSn());
            orderEvent.setAfterSaleStatus(status);
            orderEvent.setOrderAutoCancel(EnumUtils.eq(AfterSaleSourceEnum.SYSTEM, afterSale.getAfterSaleSource())
                    && EnumUtils.eq(AfterSaleTypeEnum.REFUND, afterSale.getAfterSaleType()));
            orderEvent.setRefundSuccess(Optional.ofNullable(context
                    .getChangeContentOperate()
                    .getChannelActualRefundAmount()).isPresent());
            orderEvent.setContext(context);
            SpringUtil.publishEvent(orderEvent);
        }
        return ret;
    }

    private interface Action {
        /**
         * 执行逻辑
         * @param context
         * @return
         */
        Boolean exe(AfterSaleStateContext context);
    }


    private class ToBeSentBackByBuyerAction implements Action {

        @Override
        public Boolean exe(AfterSaleStateContext context) {
            AfterSaleStateContext.ChangeContentOperate changeContent = context.getChangeContentOperate();
            CustomAssert.isTrue(Objects.nonNull(changeContent) && Objects.nonNull(changeContent.getCustomerReturnAddress()),
                    "待买家寄回,缺少寄回地址");
            AfterSaleOutBO afterSaleOut = context.getAfterSale();
            CustomAssert.isTrue(EnumUtils.eq(AfterSaleStatusEnum.CHANNEL_AUDIT_SUCCESS, afterSaleOut.getStatus())
                            || EnumUtils.eq(AfterSaleStatusEnum.WAIT_DBY_AUDIT, afterSaleOut.getStatus()),
                    "当前状态不允许该操作！");
            AfterSale afterSale = AfterSale.builder()
                    .id(afterSaleOut.getId())
                    .customerReturnAddress(afterSaleServiceConverter.convertReturnAddress(changeContent.getCustomerReturnAddress()))
                    .status(context.getCurrentAfterSaleStatus())
                    .build();
            List<AfterSaleItem> afterSaleItemList = afterSaleOut.getItems().stream().map(e -> AfterSaleItem.builder()
                    .id(e.getId())
                    .afterSaleStatus(context.getCurrentAfterSaleStatus())
                    .build()).collect(Collectors.toList());
            return persist(afterSale, afterSaleItemList);
        }
    }

    private class ToBeSubmittedForChannelAction implements Action {

        @Override
        public Boolean exe(AfterSaleStateContext context) {
            AfterSaleOutBO afterSaleOut = context.getAfterSale();
            CustomAssert.isTrue(EnumUtils.eq(AfterSaleStatusEnum.WAIT_DBY_AUDIT, afterSaleOut.getStatus())
                            || EnumUtils.eq(AfterSaleStatusEnum.WAIT_REJECT_CONFIRM, afterSaleOut.getStatus()),
                    "当前状态不允许该操作！");
            AfterSale afterSale = AfterSale.builder()
                    .id(afterSaleOut.getId())
                    .afterSaleTradeOrderSn(String.valueOf(idGeneratorSnowflake.snowflakeId()))
                    .status(context.getCurrentAfterSaleStatus())
                    .build();
            List<AfterSaleItem> afterSaleItemList = afterSaleOut.getItems().stream().map(e -> AfterSaleItem.builder()
                    .id(e.getId())
                    .afterSaleStatus(context.getCurrentAfterSaleStatus())
                    .build()).collect(Collectors.toList());
            if (Objects.nonNull(context.getChangeContentOperate())) {
                assembleUpdateInfo(afterSale, afterSaleItemList, context);
            }
            return persist(afterSale, afterSaleItemList);
        }
    }

    private class CompleteAction implements Action {

        @Override
        public Boolean exe(AfterSaleStateContext context) {
            AfterSaleOutBO afterSaleOut = context.getAfterSale();
            if (EnumUtils.eq(AfterSaleSourceEnum.SYSTEM, afterSaleOut.getAfterSaleSource())) {
                CustomAssert.isTrue(EnumUtils.eq(AfterSaleStatusEnum.TO_BE_REVIEWED_BY_CHANNEL, afterSaleOut.getStatus())
                                || EnumUtils.eq(AfterSaleStatusEnum.CHANNEL_AUDIT_SUCCESS, afterSaleOut.getStatus()),
                        "当前状态不允许该操作！");

            } else {
                CustomAssert.isTrue(EnumUtils.eq(AfterSaleStatusEnum.TO_BE_CONFIRMED_BY_USER, afterSaleOut.getStatus()), "当前状态不允许该操作！");
            }
            AfterSale afterSale = AfterSale.builder()
                    .id(afterSaleOut.getId())
                    .status(context.getCurrentAfterSaleStatus())
                    .build();
            List<AfterSaleItem> afterSaleItemList = afterSaleOut.getItems().stream().map(e -> AfterSaleItem.builder()
                    .id(e.getId())
                    .skuCode(e.getSkuCode())
                    .afterSaleStatus(context.getCurrentAfterSaleStatus())
                    .build()).collect(Collectors.toList());
            if (EnumUtils.eq(AfterSaleSourceEnum.SYSTEM, afterSaleOut.getAfterSaleSource())) {
                populateRefund(context, afterSale, afterSaleItemList);
            }
            return persist(afterSale, afterSaleItemList);
        }
    }

    private class CloseAction implements Action {

        @Override
        public Boolean exe(AfterSaleStateContext context) {
            AfterSaleOutBO afterSaleOut = context.getAfterSale();
            CustomAssert.isTrue(!(EnumUtils.eq(AfterSaleStatusEnum.CLOSE, afterSaleOut.getStatus())
                            || EnumUtils.eq(AfterSaleStatusEnum.FAIL, afterSaleOut.getStatus())
                            || EnumUtils.eq(AfterSaleStatusEnum.COMPLETED, afterSaleOut.getStatus())
                            || EnumUtils.eq(AfterSaleStatusEnum.TO_BE_CONFIRMED_BY_USER, afterSaleOut.getStatus())),
                    "当前状态不允许取消操作！");
            AfterSaleStateContext.ChangeContentOperate changeContent = context.getChangeContentOperate();
            AfterSale afterSale = AfterSale.builder()
                    .id(afterSaleOut.getId())
                    .cancelReason(changeContent.getCancelRemark())
                    .status(context.getCurrentAfterSaleStatus())
                    .build();
            List<AfterSaleItem> afterSaleItemList = afterSaleOut.getItems().stream().map(e -> AfterSaleItem.builder()
                    .id(e.getId())
                    .skuCode(e.getSkuCode())
                    .afterSaleStatus(context.getCurrentAfterSaleStatus())
                    .build()).collect(Collectors.toList());
            return persist(afterSale, afterSaleItemList);
        }
    }


    /**
     * 待收货入库
     */
    private class PendingReceiptAction implements Action {

        @Override
        public Boolean exe(AfterSaleStateContext context) {
            AfterSaleOutBO afterSaleOut = context.getAfterSale();
            CustomAssert.isTrue(EnumUtils.eq(AfterSaleStatusEnum.TO_BE_SENT_BACK_BY_BUYER, afterSaleOut.getStatus())
							|| EnumUtils.eq(AfterSaleStatusEnum.WAIT_DBY_AUDIT, afterSaleOut.getStatus())
							|| EnumUtils.eq(AfterSaleStatusEnum.TO_BE_REVIEWED_BY_CHANNEL, afterSaleOut.getStatus())
							|| EnumUtils.eq(AfterSaleStatusEnum.CHANNEL_AUDIT_SUCCESS, afterSaleOut.getStatus())
					, "当前状态不允许该操作！");
            AfterSale afterSale = AfterSale.builder()
                    .id(afterSaleOut.getId())
                    .status(context.getCurrentAfterSaleStatus())
                    .build();
            List<AfterSaleItem> afterSaleItemList = afterSaleOut.getItems().stream().map(e -> AfterSaleItem.builder()
                    .id(e.getId())
                    .afterSaleStatus(context.getCurrentAfterSaleStatus())
                    .build()).collect(Collectors.toList());
            if (persist(afterSale, afterSaleItemList)) {
                // 待收货入库，可能存在渠道上门取件，不一定有物流信息
                AfterSaleWayBillInBO wayBill = Optional.ofNullable(context.getChangeContentOperate())
                        .map(AfterSaleStateContext.ChangeContentOperate::getAfterSaleWayBill).orElse(null);
                if (Objects.nonNull(wayBill)) {
                    AfterSalesLogistic logistic = afterSaleServiceConverter.convertAfterSalesLogistic(wayBill);
                    return afterSalesLogisticsRepository.save(logistic);
                } else {
                    return true;
                }
            }
            return false;
        }
    }

    private class WaitRejectConfirmAction implements Action {
        @Override
        public Boolean exe(AfterSaleStateContext context) {
            AfterSaleOutBO afterSaleOut = context.getAfterSale();
            CustomAssert.isTrue(EnumUtils.eq(AfterSaleStatusEnum.TO_BE_SUBMITTED_FOR_CHANNEL, afterSaleOut.getStatus()) ||
                            EnumUtils.eq(AfterSaleStatusEnum.TO_BE_REVIEWED_BY_CHANNEL, afterSaleOut.getStatus()),
                    "当前状态不允许待驳回确认操作！");
            AfterSale afterSale = AfterSale.builder()
                    .id(afterSaleOut.getId())
                    .status(context.getCurrentAfterSaleStatus())
                    .failReason(Optional.ofNullable(context.getChangeContentOperate())
                            .map(AfterSaleStateContext.ChangeContentOperate::getFailReason)
                            .orElse(StringUtils.EMPTY))
                    .build();
            List<AfterSaleItem> afterSaleItemList = afterSaleOut.getItems().stream().map(e -> AfterSaleItem.builder()
                    .id(e.getId())
                    .afterSaleStatus(context.getCurrentAfterSaleStatus())
                    .build()).collect(Collectors.toList());
            return persist(afterSale, afterSaleItemList);
        }
    }


    private class ChannelAuditSuccessAction implements Action {
        @Override
        public Boolean exe(AfterSaleStateContext context) {
            AfterSaleOutBO afterSaleOut = context.getAfterSale();
            CustomAssert.isTrue(EnumUtils.eq(AfterSaleStatusEnum.TO_BE_REVIEWED_BY_CHANNEL, afterSaleOut.getStatus()),
                    "当前状态不允许该操作！");
            AfterSale afterSale = AfterSale.builder()
                    .id(afterSaleOut.getId())
                    .status(context.getCurrentAfterSaleStatus())
                    .build();
            List<AfterSaleItem> afterSaleItemList = afterSaleOut.getItems().stream().map(e -> AfterSaleItem.builder()
                    .id(e.getId())
                    .afterSaleStatus(context.getCurrentAfterSaleStatus())
                    .build()).collect(Collectors.toList());
            return persist(afterSale, afterSaleItemList);
        }
    }

    private class ToBeConfirmedByUserAction implements Action {

        @Override
        public Boolean exe(AfterSaleStateContext context) {
            AfterSaleOutBO afterSaleOut = context.getAfterSale();
            CustomAssert.isTrue(EnumUtils.eq(AfterSaleStatusEnum.WAIT_DBY_AUDIT, afterSaleOut.getStatus())
                            || EnumUtils.eq(AfterSaleStatusEnum.CHANNEL_AUDIT_SUCCESS, afterSaleOut.getStatus())
                            || EnumUtils.eq(AfterSaleStatusEnum.TO_BE_REVIEWED_BY_CHANNEL, afterSaleOut.getStatus())
                            || EnumUtils.eq(AfterSaleStatusEnum.PENDING_RECEIPT, afterSaleOut.getStatus())
                    , "当前状态不允许该操作！");
            AfterSale afterSale = AfterSale.builder()
                    .id(afterSaleOut.getId())
                    .status(context.getCurrentAfterSaleStatus())
                    .build();
            List<AfterSaleItem> afterSaleItemList = afterSaleOut.getItems().stream().map(e -> AfterSaleItem.builder()
                    .id(e.getId())
                    .skuCode(e.getSkuCode())
                    .afterSaleStatus(context.getCurrentAfterSaleStatus())
                    .build()).collect(Collectors.toList());
            populateRefund(context, afterSale, afterSaleItemList);
            return persist(afterSale, afterSaleItemList);
        }
    }

    private static void populateRefund(AfterSaleStateContext context, AfterSale afterSaleDO, List<AfterSaleItem> afterSaleItemList) {
        AfterSaleOutBO afterSale = context.getAfterSale();
        AfterSaleStateContext.ChangeContentOperate changeContent = context.getChangeContentOperate();
        if (EnumUtils.eq(AfterSaleTypeEnum.REFUND, afterSale.getAfterSaleType())
                || EnumUtils.eq(AfterSaleTypeEnum.RETURNED, afterSale.getAfterSaleType())) {
            CustomAssert.notNull(changeContent.getChannelActualRefundAmount(), "退款信息缺失");
            afterSaleDO.setChannelActualRefundAmount(changeContent.getChannelActualRefundAmount());
            afterSaleDO.setChannelFreightActualRefundAmount(changeContent.getChannelFreightActualRefundAmount());
            afterSaleDO.setRefundStatus(RefundStatusEnum.REFUND_SUCCESS.getValue());
        }
        List<AfterSaleStateContext.AfterSaleUpdateItemInfo> afterSaleItem = changeContent.getAfterSaleItemInfoList();
        if (CollectionUtils.isEmpty(afterSaleItem)) {
            return;
        }
        Map<String, AfterSaleStateContext.AfterSaleUpdateItemInfo> itemInfoMap = afterSaleItem.stream()
                .collect(Collectors.toMap(AfterSaleStateContext.AfterSaleUpdateItemInfo::getSkuCode, Function.identity()));
        afterSaleItemList.forEach(e -> {
            e.setAfterSaleStatus(context.getCurrentAfterSaleStatus());
            e.setChannelActualRefundAmount(itemInfoMap.getOrDefault(e.getSkuCode(),
                    new AfterSaleStateContext.AfterSaleUpdateItemInfo()).getChannelActualRefundAmount());
            e.setChannelFreightActualRefundAmount(itemInfoMap.getOrDefault(e.getSkuCode(),
                    new AfterSaleStateContext.AfterSaleUpdateItemInfo()).getChannelFreightActualRefundAmount());
        });
    }

    private boolean persist(AfterSale po, List<AfterSaleItem> items) {
        AtomicBoolean ret = new AtomicBoolean(false);
        ret.set(afterSaleRepository.updateById(po));
        if (ret.get()) {
            items.forEach(e -> {
                if (!ret.get()) {
                    return;
                }
                if (!afterSaleItemRepository.updateById(e)) {
                    ret.set(false);
                }
            });
        }
        return ret.get();
    }

    private class DbyAuditRejectAction implements Action {

        @Override
        public Boolean exe(AfterSaleStateContext context) {
            AfterSaleOutBO afterSaleOut = context.getAfterSale();
            CustomAssert.isTrue(EnumUtils.eq(AfterSaleStatusEnum.WAIT_DBY_AUDIT, afterSaleOut.getStatus())
                            || EnumUtils.eq(AfterSaleStatusEnum.TO_BE_REVIEWED_BY_CHANNEL, afterSaleOut.getStatus())
                            || EnumUtils.eq(AfterSaleStatusEnum.WAIT_REJECT_CONFIRM, afterSaleOut.getStatus())
                            || EnumUtils.eq(AfterSaleStatusEnum.PENDING_RECEIPT, afterSaleOut.getStatus())
                    , "当前状态不允许该操作！");
            AfterSaleStateContext.ChangeContentOperate changeContent = context.getChangeContentOperate();
            AfterSale afterSale = AfterSale.builder()
                    .id(afterSaleOut.getId())
                    .status(context.getCurrentAfterSaleStatus())
                    .failReason(changeContent.getFailReason())
                    .build();
            List<AfterSaleItem> afterSaleItemList = afterSaleOut.getItems().stream().map(e -> AfterSaleItem.builder()
                    .id(e.getId())
                    .afterSaleStatus(context.getCurrentAfterSaleStatus())
                    .build()).collect(Collectors.toList());
            return persist(afterSale, afterSaleItemList);
        }
    }

    private class ToBeReviewedByChannelAction implements Action {

        @Override
        public Boolean exe(AfterSaleStateContext context) {

            String channelAfterSaleSn = Optional.ofNullable(context.getChangeContentOperate())
                    .map(AfterSaleStateContext.ChangeContentOperate::getChannelAfterSaleSn)
                    .orElse(StringUtils.EMPTY);
            CustomAssert.hasLength(channelAfterSaleSn, "渠道售后编码缺失");

            AfterSaleOutBO afterSaleOut = context.getAfterSale();
            CustomAssert.isTrue(EnumUtils.eq(AfterSaleStatusEnum.TO_BE_SUBMITTED_FOR_CHANNEL, afterSaleOut.getStatus()),
                    "当前状态不允许该操作！");
            AfterSale afterSale = AfterSale.builder()
                    .id(afterSaleOut.getId())
                    .status(context.getCurrentAfterSaleStatus())
                    .channelAfterSaleSn(channelAfterSaleSn)
                    .build();
            List<AfterSaleItem> afterSaleItemList = afterSaleOut.getItems().stream().map(e -> AfterSaleItem.builder()
                    .id(e.getId())
                    .afterSaleStatus(context.getCurrentAfterSaleStatus())
                    .build()).collect(Collectors.toList());
            return persist(afterSale, afterSaleItemList);
        }
    }

    private void assembleUpdateInfo(AfterSale po, List<AfterSaleItem> items, AfterSaleStateContext context) {
        AfterSaleStateContext.ChangeContentOperate changeContent = context.getChangeContentOperate();
        List<AfterSaleStateContext.AfterSaleUpdateItemInfo> afterSaleItemInfoList = changeContent.getAfterSaleItemInfoList();
        if (CollectionUtils.isEmpty(afterSaleItemInfoList)) {
            return;
        }
        Map<String, AfterSaleStateContext.AfterSaleUpdateItemInfo> itemsInfoMap = afterSaleItemInfoList
                .stream().collect(Collectors.toMap(AfterSaleStateContext.AfterSaleUpdateItemInfo::getSkuCode, Function.identity()));
        po.setFreightApplyRefundAmount(changeContent.getFreightApplyRefundAmount());
        AfterSaleOutBO afterSale = context.getAfterSale();
        Map<Long, AfterSaleItemOutBO> saleItemOutMap = afterSale.getItems()
                .stream()
                .collect(Collectors.toMap(AfterSaleItemOutBO::getId, Function.identity()));
        for (AfterSaleItem afterSaleItem : items) {
            AfterSaleStateContext.AfterSaleUpdateItemInfo item = itemsInfoMap.getOrDefault(afterSaleItem.getSkuCode(),
                    new AfterSaleStateContext.AfterSaleUpdateItemInfo());
            AfterSaleItemOutBO afterSaleItemOut = saleItemOutMap.get(afterSaleItem.getId());
            afterSaleItem.setAfterSaleStatus(context.getCurrentAfterSaleStatus());
            afterSaleItem.setGoodsStatus(item.getGoodsStatus());
            if (Objects.isNull(item.getChannelApplyAfterSaleAmount())) {
                afterSaleItem.setApplyRefundAmount(afterSaleItemOut.getApplyRefundAmount());
            } else {
                afterSaleItem.setApplyRefundAmount(item.getChannelApplyAfterSaleAmount());
            }
            afterSaleItem.setFreightApplyRefundAmount(item.getFreightApplyRefundAmount());
            afterSaleItem.setReasonName(item.getReasonName());
            afterSaleItem.setReasonCode(item.getReasonCode());
        }
        po.setApplyRefundAmount(items.stream().map(e -> Optional.ofNullable(e.getApplyRefundAmount()).orElse(BigDecimal.ZERO))
                .reduce(BigDecimal.ZERO, BigDecimal::add));
    }
}
